package com.xiaoshuidi.cloud.module.bpm.framework.dateformat;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 *
 * @author tangjizhouchn@foxmail.com
 * @date 2019-08-18
 */
@Slf4j
@ControllerAdvice
public class DateFormatAdvice {

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if(ObjectUtil.isEmpty(text)) return;
                setValue(Instant.ofEpochMilli(Long.valueOf(text)).atZone(ZoneOffset.ofHours(8)).toLocalDate());
            }
        });

        webDataBinder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if(ObjectUtil.isNotEmpty(text)){
                    try {
                        setValue(Instant.ofEpochMilli(Long.valueOf(text)).atZone(ZoneOffset.ofHours(8)).toLocalDateTime());
                    } catch (NumberFormatException e) {
                        setValue(text);
                    }
                }
            }
        });
    }
}

